/**
 * 支付路由
 * 定义支付相关的RESTful API路由
 */
const express = require('express');
const router = express.Router();
const asyncHandler = require('../utils/asyncHandler');
const CustomError = require('../utils/customError');
const OrderService = require('../services/order.service');

/**
 * @swagger
 * /api/pay/webChat/{orderNo}/create: 
 *   get: 
 *     summary: 获取微信支付预支付信息
 *     tags: [支付管理]
 *     parameters:
 *       - in: path
 *         name: orderNo
 *         required: true
 *         schema:
 *           type: string
 *         description: 订单号
 *     responses:
 *       200: 
 *         description: 获取成功
 */
router.get('/webChat/:orderNo/create', asyncHandler(async (req, res, next) => {
  const { orderNo } = req.params;
  
  // 获取用户ID（实际项目中应从token中获取，这里为了测试方便从环境变量获取）
  const userId = process.env.TEST_USER_ID || 1;
  
  // 验证订单是否存在
  const order = await OrderService.getOrderDetail(orderNo, userId);
  
  if (!order) {
    throw new CustomError('订单不存在', 404);
  }
  
  // 模拟微信支付预支付信息（实际项目中应调用微信支付API）
  const prepayInfo = {
    appId: 'wx1234567890abcdef',
    timeStamp: Math.floor(Date.now() / 1000).toString(),
    nonceStr: Math.random().toString(36).substring(2, 15),
    package: `prepay_id=wx${Date.now()}`,
    signType: 'RSA',
    paySign: 'oR9d8PuhnIc+YZ8cBHFCwA...'
  };
  
  res.status(200).json({
    code: 200,
    message: '获取成功',
    data: prepayInfo
  });
}));

/**
 * @swagger
 * /api/pay/webChat/{orderNo}/status: 
 *   get: 
 *     summary: 查询支付状态
 *     tags: [支付管理]
 *     parameters:
 *       - in: path
 *         name: orderNo
 *         required: true
 *         schema:
 *           type: string
 *         description: 订单号
 *     responses:
 *       200: 
 *         description: 查询成功
 */
router.get('/webChat/:orderNo/status', asyncHandler(async (req, res, next) => {
  const { orderNo } = req.params;
  
  // 获取用户ID（实际项目中应从token中获取，这里为了测试方便从环境变量获取）
  const userId = process.env.TEST_USER_ID || 1;
  
  // 验证订单是否存在
  const order = await OrderService.getOrderDetail(orderNo, userId);
  
  if (!order) {
    throw new CustomError('订单不存在', 404);
  }
  
  // 模拟查询支付状态（实际项目中应调用微信支付API）
  const payStatus = order.status === 2 ? 'PAID' : 'UNPAID';
  const payTime = order.status === 2 ? new Date().toISOString().slice(0, 19).replace('T', ' ') : null;
  
  // 如果订单状态是待付款，模拟支付成功，更新订单状态
  if (order.status === 1) {
    await OrderService.payOrder(orderNo, userId);
  }
  
  res.status(200).json({
    code: 200,
    message: '查询成功',
    data: {
      orderNo,
      payStatus,
      payTime,
      transactionId: payStatus === 'PAID' ? `420000012320230501${Date.now()}` : null
    }
  });
}));

module.exports = router;